<template>
  <el-form ref="ruleFormRef" @submit.prevent="uiMethods.searchFriend(ruleFormRef)" :model="uiForm.searchForm"
    :rules="rules" class="demo-ruleForm" :size="formSize" status-icon>
    <el-form-item prop="keyWord">
      <span class="w-75">
        <el-input placeholder="请输入用户名或昵称" v-model="uiForm.searchForm.keyWord" /></span>
      <span class="ms-3">
        <el-button type="primary" native-type="submit">
          搜索
        </el-button>
      </span>
    </el-form-item>
  </el-form>
  <el-scrollbar :height="340">
    <el-row v-if="uiData.userList.length === 0">暂无数据~</el-row>
    <el-row v-if="uiData.userList.length > 0">
      <el-col v-for="(item, index) in uiData.userList" :index="index" class="mb-3" style="height: 70px" :span="12">
        <el-row>
          <el-col :span="7"><el-avatar :size="45" :src="uiData.defaultAvatar" /></el-col>
          <el-col :span="17">
            <el-row class="text-truncate">
              {{ item.name }}
            </el-row>
            <el-row class="text-truncate">
              {{ item.username }}
            </el-row>
            <el-row class="mt-1">
              <el-button size="small" :type="item.isFriend === 1 ? 'success' : 'primary'"
                @click="uiMethods.addFriend(item.id)" :disabled="item.isFriend === 1 ? true : false">
                {{ item.isFriend === 1 ? '已添加' : '添加好友' }}
              </el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import axios, { AxiosResponse } from 'axios';
import { FormInstance, FormRules } from 'element-plus/es/components/form';
import { reactive, ref, onMounted } from 'vue';
import { useStore } from '../common/piniaStore';

import { defaultAvatar } from '../common/resource';

const store = useStore();

const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  keyWord: string;
}

console.log('图片：', defaultAvatar);

const rules = reactive<FormRules<RuleForm>>({
  keyWord: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
});

const uiForm = ref({
  searchForm: {
    keyWord: ''
  }
});

const uiData = ref({
  defaultAvatar: defaultAvatar,
  userList: [
    {
      name: '测试1',
      username: 'test1',
      id: '123455',
      isFriend: 0
    }
  ]
});

onMounted(() => {
  uiData.value.userList = [];
});

let timeoutId: NodeJS.Timeout | null = null;

const uiMethods = {
  searchFriend: async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
      if (!valid) {
        console.log('表单验证失败', fields);
        return;
      }
      const res: AxiosResponse<any, any> = await axios.get('/searchUser', {
        params: {
          keyWord: uiForm.value.searchForm.keyWord
        }
      });

      uiData.value.userList = res.data.data;
    });
  },

  /**
   * 添加好友，做了防抖
   * @param friendId 好友id
   */
  addFriend: async (friendId: string) => {
    // 如果已经有一个待执行的调用，那么清除它
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    // 创建一个新的调用，并在1秒后执行
    timeoutId = setTimeout(() => {
      store.client?.applyAddFriend(friendId);
    }, 350);
  }
};

</script>

<style lang="scss" scoped></style>
